package controller;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import dao.DormitoryDao;
import dao.impl.DormitoryDaoImpl;
import entity.Dormitory;
import entity.Student;
import service.DormitoryService;
import service.impl.ClockServicelmpl;
import service.impl.DormitoryServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/DormitoryController")
public class DormitoryController extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        HttpSession session=req.getSession();
        String op=req.getParameter("op");
        PrintWriter out=resp.getWriter();
        if(op.equals("cx")){
            String lid = req.getParameter("lid");
            String pageStr = req.getParameter("page");
            int page = StringUtils.isNullOrEmpty(pageStr) ? 0 : Integer.parseInt(pageStr);
            int pageSize = 2; // 每页2条记录

            DormitoryDao dsd = new DormitoryDaoImpl();
            List<Dormitory> list = null;
            int totalCount = 0;

            try {
                Integer lidParam = StringUtils.isNullOrEmpty(lid) ? null : Integer.valueOf(lid);
                totalCount = dsd.getTotalCount(lidParam);
                int totalPages = (totalCount + pageSize - 1) / pageSize;
                list = dsd.cx(lidParam, page, pageSize);

                Map<String, Object> result = new HashMap<>();
                result.put("list", list);
                result.put("page", page);
                result.put("totalPages", totalPages);
                result.put("totalCount", totalCount);

                out.write(JSON.toJSONString(result));
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库操作失败");
            }
        }else  if (op.equals("sc")){
            DormitoryDao dsd = new DormitoryDaoImpl();
            try {
                String dormId = req.getParameter("id");
                if (dormId != null && !dormId.isEmpty()) {
                    int isSuccess = dsd.sc(Integer.parseInt(dormId));

                    // 添加删除结果响应
                    if(isSuccess > 0) {
                        out.write("删除成功");
                    } else {
                        out.write("删除失败，记录不存在");
                    }

                    List<Dormitory> list = dsd.cx1(0);
                    session.setAttribute("list", list);
                } else {
                    out.write("宿舍ID不能为空");
                }
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
                out.write("删除失败：" + e.getMessage());
            }
        } else if (op.equals("add")) {
            // 添加参数验证
            String name=req.getParameter("name");
            String address=req.getParameter("address");
            String manager_id=req.getParameter("manager_id");
            String total_floors=req.getParameter("total_floors");

            if(name == null || name.isEmpty() ||
                    address == null || address.isEmpty() ||
                    manager_id == null || manager_id.isEmpty() ||
                    total_floors == null || total_floors.isEmpty()) {
                out.write("所有字段都不能为空");
                return;
            }

            DormitoryService dsd=new DormitoryServiceImpl();
            try {
                dsd.tj(name,address,Integer.parseInt(manager_id),Integer.parseInt(total_floors));
                out.write("添加成功");
            } catch (SQLException e) {
                e.printStackTrace();
                out.write("添加失败：" + e.getMessage());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                out.write("添加失败：" + e.getMessage());
            } catch (NumberFormatException e) {
                out.write("参数格式错误");
            }
        } else if (op.equals("update")) {
            String name = req.getParameter("name");  // 作为查询条件的building_name
            String address = req.getParameter("address");
            String manager_id = req.getParameter("manager_id");
            String total_floors = req.getParameter("total_floors");
            String building_id = req.getParameter("id");
            DormitoryService dsd = new DormitoryServiceImpl();
            try {
                // 调用修改方法，使用building_name作为条件
                int success = dsd.xg(name, address,
                        Integer.parseInt(manager_id),
                        Integer.parseInt(total_floors), Integer.parseInt(building_id));

                if (success>0) {
                    out.write("修改成功");
                } else {
                    out.write("修改失败，记录不存在");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                out.write("修改失败，数据库错误");
            } catch (NumberFormatException | ClassNotFoundException e) {
                e.printStackTrace();
                out.write("修改失败，参数格式错误");
            }
        }
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
